<?php
/**
 *  国家和地区管理
*/

namespace app\api\service;

use app\api\model\LogisticsRules;
use app\api\model\RegionCity;
use app\api\model\RegionCountry;

use app\facade\Basic;



class Region
{

    /**
     *  获取国家列表
    */
    public function getCountryList()
    {
//        $result = LogisticsRules::where([
//            'is_del' => 0,
//            'status' => 1
//        ])->field('to_nation')->select();
//
//        if(empty($result)) {
//            return Basic::data(1,'common.error');
//        }
//
//        $result = $result->toArray();
//
//        $ids = array_column($result, 'to_nation');
//   ->where('id','in',$ids)
        $result = RegionCountry::field('id,name,country_code,full_name,code')->select();
        return Basic::data(0,'common.success',$result);
    }
    /**
     *  获取国家列表
     */
    public function getMobilePrefix()
    {
        $result = [];
        $list = RegionCountry::field('mobile_prefix')->select()->toArray();
        $list = array_unique(array_column($list,'mobile_prefix'));
        foreach ($list as $value){
            $result[] = ['text'=>'+'.$value,'value'=>'+'.$value];
        }
        return Basic::data(0,'common.success',$result);
    }
    /**
     *  获取城市
    */
    public function getCityList($param)
    {
        $result = RegionCity::where('country_id',$param['country_id'])->field('id,state,name,lower_name')->select();
        return Basic::data(0,'common.success',$result);
    }

    /**
     *  获取省和城市
    */
    public function area($param)
    {

        $result = RegionCity::where('country_id',$param['country_id'])->field('id,state,name,lower_name,state_code')->select();

        if( !$result ) {
            return Basic::data(0,'common.success',[]);
        }

        $result = $result->toArray();


        $result_all = [];
        foreach ($result as $value) {
            $result_all[$value['state']][] = $value;
        }




        $state = [];
        $city = [];
        $i = 0;
        $ii = 0;
        foreach ($result_all as $key=>$item) {

            foreach ($item as $value){

                if ($key!=''){
                    $state[$i]['id'] = $value['state_code'];
                    $state[$i]['name'] = $value['state'];
                }

                $city[$ii]['id'] = $value['id'];
                $city[$ii]['name'] = $value['name'];
                $city[$ii]['state_id'] = !empty($value['state_code']) ? $value['state_code'] : '';

                $ii++;
            }
            $i ++;
        }




        return Basic::data(0,'common.success',[
            'state' => $state,
            'city' => $city,
        ]);

    }

}
